package com.bayihouse.utils;

import org.apache.commons.lang3.StringUtils;
import org.python.antlr.ast.Str;

import java.util.HashMap;
import java.util.Map;

public class AddressUtils {


    public static String regx = "^[\\s\\S]*号[\\s\\S]*小区[\\s\\S]*号楼[\\s\\S]*单元[\\s\\S]*室$";



    public static boolean isBusinessUsing(String nowAddress) {
        if (!StringUtils.isNotBlank(nowAddress)) {
            return false;
        }
        return !nowAddress.matches(regx);
    }


    public static String[] getNowAddressArray(String nowAddress) throws Exception {
        if (isBusinessUsing(nowAddress)) {
            return getNowAddressArrayBusiness(nowAddress);
        }else {
            return getNowAddressArrayLiving(nowAddress);
        }
    }



    public static String[] getNowAddressArrayLiving(String nowAddress) {
        String text = nowAddress;
        text = MyStringUtils.getDeleteMarkStr(text);
        int strlen = text.length();
        String[] splits = {"号","小区","号楼","单元","室"};
        Integer[] splitLen = {1,2,2,2,1};
        String[] res = new String[5];
        int targetIndex = 0;
        int index = 0;
        int start = 0;
        for (int i = 0; i < strlen;) {
            while (i < strlen && index < splitLen[targetIndex] && text.charAt(i) == splits[targetIndex].charAt(index)) {
                index++;
                i++;
            }
            if (index == splitLen[targetIndex]) {
                res[targetIndex] = text.substring(start, i - splitLen[targetIndex]) + splits[targetIndex];
                targetIndex++;
                start = i;
            }else{
                i++;
            }
            index = 0;
        }
        return res;
    }


    public static String[] getNowAddressArrayBusiness(String nowAddress) throws Exception {
        String[] splitStr = nowAddress.split("号");
        if(splitStr.length == 1) {
            throw new Exception("地址解析错误");
        }
        String[] splits = new String[3];
        String res2 = "";
        for (int i = 1; i < splitStr.length; i++) {
            res2 += splitStr[i];
        }
        splits[0] = getCommunityName(splitStr[0]);
        splits[1] = splitStr[0];
        splits[2] = res2;
        return splits;
    }


    public static String getCommunityName(String text) {
        int len = text.length();
        int end = 0;
        for (; end < len; end++) {
            if (text.charAt(end) >= '0' && text.charAt(end) <= '9') {
                break;
            }
        }
        return text.substring(0, end);
    }


}
